use std::cell::RefCell;
use std::rc::Rc;
use yew::{function_component, html, use_context, use_state, Callback, Html};
use yew_hooks::{use_local_storage};
use yewdux::{use_dispatch, use_store};
use crate::db::pojo::pojo::ImSession;
use crate::business::app_state::{AppState};
use crate::business::page::fragment::im_session_list_view::{ImSessionListView, SessionListState};
use crate::business::page::fragment::message_list_view::MessageListView;
use crate::business::page::fragment::nav::NavLinkIndicator;
use crate::business::service::message_read_service::MessageReadService;
use crate::business::util::util::get_login_info;

#[function_component(SessionMessagePage)]
pub fn session_message_page() -> Html {
    let app_state = use_context::<AppState>().unwrap();
    let app_state_clone = app_state.clone();

    let other_select_session = use_state(|| SelectSessionData::default());
    let select_session_clone = other_select_session.clone();
    let select_session_callback = Callback::from(move |session: ImSession| {
        log::info!("selected session {:?}, {:?}", session, select_session_clone);
        let select_data = SelectSessionData::new(Some(Rc::new(RefCell::new(session))), select_session_clone.count+1);
        select_session_clone.set(select_data);
    });

    let ss = other_select_session.clone();

    let (_, dispatch) = use_store::<NavLinkIndicator>();
    dispatch.reduce_mut(|store| store.value = "_MessageSession_");

    let local_storage = use_local_storage::<String>("_login_".to_string());
    let user_id = match get_login_info(local_storage) {
        None => {None}
        Some(token) => {
            Some(token.use_id)
        }
    };

    let session_dispatch = use_dispatch::<SessionListState>();
    let message_read_service = use_state(|| MessageReadService::new(user_id.clone().unwrap(), app_state_clone.clone(), session_dispatch.clone()));

    html! {
        <div class="session-message-page">
            <ImSessionListView select_session_callback = {select_session_callback}/>

            <MessageListView select_session = { ss.select_session.clone() } count = { ss.count}
                message_read_handle = {message_read_service.clone()}/>
        </div>
    }
}

#[derive(Debug, Default, Clone)]
struct SelectSessionData {
    select_session: Option<Rc<RefCell<ImSession>>>,
    count: usize,
}

impl SelectSessionData {
    pub fn new(other_select_session: Option<Rc<RefCell<ImSession>>>, count: usize) -> Self {
        Self {
            select_session: other_select_session,
            count,
        }
    }

    pub fn increase_count(&mut self) {
        self.count += 1;
    }
}